package com.example.filter;

import com.alibaba.fastjson.JSON;
import com.example.pojo.vo.LoginUser;
import com.example.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.rmi.RemoteException;
/**
 * @author crt
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if(uri.equals("/user/login")||uri.equals("/user/register")){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            throw new RemoteException("token为空");
        }
        LoginUser loginUser = null;
        //校验
        try {
            //从Redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if(redisToken == null){
                //token已失效
                throw new RuntimeException();
            }
            Claims claims = JwtUtil.parseJWT(token);
            String loginUserString = claims.getSubject();
            //字符串转LoginUser对象
            loginUser = JSON.parseObject(loginUserString, LoginUser.class);
            System.out.println(loginUser.toString());
//            filterChain.doFilter(request,response);
        } catch (Exception e) {
            throw new RuntimeException("token校验失败");
        }
        //把用户信息放入security上下文
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行
        filterChain.doFilter(request,response);
    }
}
